using System;
using System.Web;
using SoftwareMonkeys.Scriptech.Diagnostics;

namespace SoftwareMonkeys.Scriptech.Web
{
	public class ScriptHttpHandler : IHttpHandler
	{
		public bool IsReusable {
			get { return false; }
		}

		private ScriptRouteHandler routeHandler;

		public ScriptHttpHandler (ScriptRouteHandler routeHandler)
		{
			this.routeHandler = routeHandler;
			
			if (routeHandler.VirtualPath == null || routeHandler.VirtualPath == String.Empty)
				throw new Exception("VirtualPath property must be set.");
			
		}

		public void ProcessRequest (HttpContext context)
		{
			using (LogGroup logGroup = LogGroup.StartDebug("Processing request via script HTTP handler."))
			{
				string path = routeHandler.VirtualPath;
				
				if (path == null || path == String.Empty)
					throw new Exception("VirtualPath property must be set.");
				
				LogWriter.Debug("Path: " + path);
				
				// TODO: Check if query string is needed
				string queryString = HttpContext.Current.Request.Url.Query;
				
				LogWriter.Debug("Query string: " + queryString);
				
				try
				{
					Redirector.Go(context, path, true);
				}
				catch (Exception ex)
				{
					LogWriter.Error(ex);
			
					throw;
				}
			}
		}
	}
}

